// 表单设计
import { calculateBoxAreaStyle, getColumnMinimums, canMergeCells, calculateSpan, hideOtherCells } from '@/views/designer/util.js';
import { letters } from '@/views/designer/data.js';
import { getDetail, add } from '@/api/designer/apaasList';
import { getApiList } from '@/api/quality/examine-api-flow-config';
import { Message } from 'element-ui';

const designer = {
  namespaced: true,
  state: {
    dataJson: {
      id: '',
      rows: [],
      colgroupWidth: [],
      merges: [],
      name: '',
      type: '',
      printConfig: {},
      tableTotalWidth: 0
    },
    apiJson: [],
    submitJson: {},
    dictJson: [],
    xAxisNum: [],
    yAxisNum: [],
    histroyData: [], // 编辑器快照数据
    histroyIndex: 0,
    coordArray: [], // 单元格坐标集合
    apiAllList: [], // 所有接口
    // 初始化表格属性
    baseTableConfig: {
      rows: 10,
      columns: 10,
      cellWidth: 100,
      cellHeight: 30
    },
    // 选中单元格属性
    cellInfo: {
      x: '',
      y: '',
      xName: '',
      isLock: false,
      merge: [],
      type: 'text',
      dicCode: '',
      dicData: [],
      code: '',
      value: '',
      apiField: false,
      style: {}
    },
    // 框选区域
    boxAreaXY: {
      startX: 0,
      startY: 0,
      endX: 0,
      endY: 0,
      width: 1,
      height: 1
    },
    letters: letters
  },
  getters: {
    dicData: (state) => {
      return JSON.stringify(state.dictJson, null, 2);
    }
  },
  actions: {
    async getFormTemplate({ commit }, payload) {
      try {
        commit('clearDesignerData');
        const res = await getDetail(payload.id);
        const data = res.data.data || {};
        let content = {};
        content = JSON.parse(data.content || '{}');
        content.id = data.id;
        content.name = data.name;
        content.type = data.type;
        if (content.rows && content.rows.length > 0) {
          content.rows.forEach((row) => {
            row.cells.forEach((cell) => (cell.isEdit = false));
          });
        }
        commit('renderForm', content);
        commit('renderApiJson', JSON.parse(data.apiJson || '[]'));
        commit('renderSubmitJson', JSON.parse(data.submitJson || '{}'));
        commit('setDictJson', JSON.parse(data.dictJson || '[]'));
        return data;
      } catch (error) {
        console.error(error);
        throw error;
      }
    },
    async getApiList({ commit }) {
      try {
        const res = await getApiList({ apiType: 'QUERY' });
        commit('setApiList', res.data.data);
        return res.data.data;
      } catch (error) {
        console.error(error);
        throw error;
      }
    },
    setDataJson({ commit }, payload) {
      commit('renderForm', payload);
    },
    setSubmitJson({ commit }, payload) {
      commit('renderSubmitJson', payload);
    },
    saveForm({ state, commit }, { apiJson, dataJson, submitJson, dictJson }) {
      let apiArray = [];
      if (apiJson && apiJson.length > 0) {
        apiArray = apiJson.map((item) => {
          return {
            id: item.id,
            code: item.code,
            name: item.name,
            url: item.url,
            relyOtherApi: item.relyOtherApi,
            showQuery: item.showQuery,
            paramsForm: item.paramsForm
          };
        });
      }
      let colgroupWidth = state.xAxisNum.map((item) => item.width);
      dataJson.colgroupWidth = colgroupWidth;
      console.log(dataJson.rows, 'dataJson.rows');
      add({
        id: dataJson.id,
        name: dataJson.name,
        type: dataJson.type,
        content: JSON.stringify(dataJson),
        apiJson: JSON.stringify(apiArray),
        submitJson: JSON.stringify(submitJson),
        dictJson: JSON.stringify(dictJson)
      })
        .then((res) => {
          Message.success('保存成功');
        })
        .catch((err) => {
          console.error('保存失败:', err);
        });
    }
  },
  mutations: {
    initFormTemplate(state) {
      state.dataJson = {
        id: '',
        rows: [],
        colgroupWidth: [],
        merges: [],
        name: '',
        type: '',
        printConfig: {},
        tableTotalWidth: 0
      };
      state.apiJson = [];
      state.submitJson = {};
      state.dictJson = [];
      state.histroyData = [];
      state.histroyIndex = 0;
      state.xAxisNum = [];
      state.yAxisNum = [];
    },
    renderForm(state, data) {
      state.dataJson = structuredClone(data);
      if (data.rows && data.rows.length > 0) {
        this.commit('form/initAxis', {
          cellWidth: state.baseTableConfig.cellWidth,
          cellHeight: state.baseTableConfig.cellHeight
        });
        state.histroyData = [];
        state.histroyIndex = 0;
        this.commit('form/addHistroyData', {
          type: 'renderForm',
          data: structuredClone(state.dataJson)
        });
      }
    },
    renderApiJson(state, data) {
      state.apiJson = data;
    },
    initForm(state, config) {
      let { rows, columns, cellWidth, cellHeight } = config;
      // 更新基础表格配置
      Object.assign(state.baseTableConfig, { rows, columns, cellWidth, cellHeight });

      // 创建初始化单元格结构
      state.dataJson.rows = Array.from({ length: rows }, (_, rowIndex) => ({
        height: cellHeight,
        cells: Array.from({ length: columns }, (_, colIndex) => ({
          code: '',
          value: '',
          type: 'text',
          dicData: [],
          dicCode: '',
          isLock: false,
          x: colIndex,
          y: rowIndex,
          merge: [1, 1],
          style: { width: cellWidth, height: cellHeight },
          eventConfig: {}
        }))
      }));

      state.dataJson.merges = [];
      state.dataJson.colgroupWidth = new Array(columns).fill(cellWidth);

      // 初始化坐标轴和相关设置
      this.commit('form/initAxis', {
        cellWidth,
        cellHeight
      });

      state.histroyIndex = 0;
      state.histroyData = [];

      this.commit('form/clearCellInfo');
      this.commit('form/clearBoxAreaXY');
      // 添加到历史记录
      this.commit('form/addHistroyData', {
        type: 'initTable',
        data: structuredClone(state.dataJson)
      });
    },
    // 初始化坐标轴
    initAxis(state, { cellWidth, cellHeight }) {
      // 重置坐标数组
      state.xAxisNum = [];
      state.yAxisNum = [];
      state.coordArray = [];
      // 初始化Y轴和坐标数组
      state.dataJson.rows.forEach((row, rowIndex) => {
        // row.height = Math.min(...row.cells.map(item => item.style.height))
        state.yAxisNum.push({
          height: row.height || cellHeight, // 使用行定义的高度或默认高度
          index: rowIndex + 1,
          active: false
        });

        // 同时构建coordArray
        row.cells.forEach((_, colIndex) => {
          state.coordArray.push(state.letters[colIndex] + (rowIndex + 1));
        });
      });

      let minArray = state.dataJson.rows.map((rItem) => {
        return rItem.cells.map((cItem) => {
          return cItem.style.width;
        });
      });
      let minWidthArray = getColumnMinimums(minArray);
      state.dataJson.colgroupWidth = minWidthArray;

      for (let i = 0; i < minWidthArray.length; i++) {
        state.xAxisNum.push({
          label: state.letters[i],
          width: minWidthArray[i],
          index: i + 1,
          active: false
        });
      }
      // 更新表格的总宽度
      this.commit('form/setTableTotalWidth');
    },
    // 更新表格的总宽度
    setTableTotalWidth(state) {
      let totalFormWidth = state.dataJson.colgroupWidth.reduce((pre, cur) => {
        return pre + cur;
      }, 0);
      state.dataJson.tableTotalWidth = totalFormWidth;
    },
    setCellInfo(state, data) {
      state.cellInfo = data;
    },
    clearCellInfo(state) {
      state.cellInfo = {
        type: 'text',
        x: '',
        y: '',
        xName: '',
        isLock: false,
        isEdit: false,
        apiField: false,
        isForamtter: false,
        code: '',
        value: '',
        dicCode: '',
        dicData: [],
        merge: [],
        url: '',
        dataType: '1',
        dataFormatter: '',
        method: 'post',
        query: '',
        btnAddRowField: '',
        eventConfig: {},
        style: {}
      };
    },
    // 新增api
    setApiJson(state, data) {
      state.apiJson.push(data);
    },
    // 编辑api
    changeApiJson(state, config) {
      let { index, data } = config;
      state.apiJson.splice(index, 1, data);
    },
    deleteApiJson(state, index) {
      state.apiJson.splice(index, 1);
    },
    renderSubmitJson(state, data) {
      state.submitJson = data;
    },
    setDictJson(state, data) {
      state.dictJson = data;
    },
    setApiList(state, data) {
      state.apiAllList = data;
    },
    lock(state, config) {
      state.cellInfo.isLock = true;
      state.dataJson.rows[state.cellInfo.y - 1].cells[state.cellInfo.x - 1].isLock = true;
    },
    unlock(state, config) {
      state.cellInfo.isLock = false;
      state.dataJson.rows[state.cellInfo.y - 1].cells[state.cellInfo.x - 1].isLock = false;
    },
    merge(state, config) {
      // 检查是否能合并单元格
      if (!canMergeCells(state)) {
        Message.error('禁止在已经合并的单元格上再次合并');
        return false;
      }

      let startCell = state.dataJson.rows[state.boxAreaXY.startY].cells[state.boxAreaXY.startX];

      const { colspan, rowspan } = calculateSpan(state);

      let { width: mergeWidth, height: mergeHeight } = calculateBoxAreaStyle(state.xAxisNum, state.yAxisNum, state.boxAreaXY);

      // 更新起始单元格的合并属性和样式
      Object.assign(startCell, {
        merge: [rowspan, colspan],
        style: { width: mergeWidth, height: mergeHeight }
      });

      // 隐藏其他单元格
      hideOtherCells(state);

      // 更新当前选择单元格的信息
      Object.assign(state.cellInfo, {
        style: { width: mergeWidth, height: mergeHeight },
        x: state.boxAreaXY.startX + 1,
        y: state.boxAreaXY.startY + 1,
        xName: state.xAxisNum[state.boxAreaXY.startX].label,
        value: startCell.value,
        merge: startCell.merge
      });

      this.commit('form/initAxis', {
        cellWidth: state.baseTableConfig.cellWidth,
        cellHeight: state.baseTableConfig.cellHeight
      });

      this.commit('form/addHistroyData', {
        type: 'merge',
        data: structuredClone(state.dataJson)
      });
    },
    split(state, config) {
      let mergeX = state.cellInfo.merge[0];
      let mergeY = state.cellInfo.merge[1];
      let cellData = state.dataJson.rows[state.cellInfo.y - 1].cells[state.cellInfo.x - 1];
      cellData.merge = [1, 1];
      cellData.style.width = state.baseTableConfig.cellWidth;
      cellData.style.height = state.baseTableConfig.cellHeight;

      for (let i = state.cellInfo.y - 1; i < state.cellInfo.y + mergeX - 1; i++) {
        state.dataJson.rows[i].cells
          .filter((cItem, cIndex) => {
            return cIndex >= state.cellInfo.x - 1 && cIndex < state.cellInfo.x + mergeY - 1;
          })
          .map((ccItem) => {
            if (ccItem.mergeCell) {
              delete ccItem.mergeCell;
            }
            ccItem.hide = false;
          });
      }

      this.commit('form/addHistroyData', {
        type: 'split',
        data: structuredClone(state.dataJson)
      });
    },
    deleteRows(state, config) {
      const that = this;
      let { index, count = 1 } = config;
      if (count == state.dataJson.rows.length) {
        state.dataJson.rows = [];
      } else {
        if (count == 1) {
          deleteSingleRow(index, 'single');
        } else {
          // 删除多行逻辑 从index+count-1行删除到index行
          for (let i = index + count - 1; i >= index; i--) {
            deleteSingleRow(i, 'multiline');
          }
        }
        // 删除单行逻辑
        function deleteSingleRow(index, mode = 'single') {
          let cells = [];
          // 针对当前行的处理逻辑
          state.dataJson.rows[index].cells.map((cItem, cIndex, array) => {
            if (!cItem.hide && cItem.merge[0] == 1 && cItem.merge[1] == 1) {
              // 显示和未合并的格子不做任何处理
              return false;
            } else {
              if (cItem.mergeCell) {
                cells.push(cItem.mergeCell);
              } else {
                if (!cItem.hide) {
                  cells.push(cItem.x + '-' + cItem.y);
                }
              }
            }
          });
          let setCells = [...new Set(cells)];
          let sameSetCells = [];
          state.dataJson.rows[index].cells.map((cItem, cIndex, array) => {
            if (setCells.includes(cItem.x + '-' + cItem.y)) {
              sameSetCells.push(cItem.x + '-' + cItem.y);
            }
          });
          let otherSetCells = setCells.filter((item) => !sameSetCells.includes(item));
          // sameSetCells：当前单元格和左上单元格是同一个单元格，向下找单元格，将其rowspan-1
          if (sameSetCells.length > 0) {
            sameSetCells.map((sItem) => {
              let [x, y] = sItem.split('-');
              x = Number(x);
              y = Number(y);
              if (y + 1 < state.dataJson.rows.length && state.dataJson.rows[y].cells[x].merge[0] > 1) {
                let cellInfo = state.dataJson.rows[y + 1].cells[x];
                cellInfo.merge[0] = state.dataJson.rows[y].cells[x].merge[0] - 1;
                cellInfo.merge[1] = state.dataJson.rows[y].cells[x].merge[1];
                cellInfo.hide = false;
                delete cellInfo.mergeCell;
                let newHeight = calculateMergeCellHeight(y + 1, cellInfo.merge);
                cellInfo.style.height = newHeight;
              }
            });
          }
          // otherSetCells：当前单元格rowspan-1
          if (otherSetCells.length > 0) {
            otherSetCells.map((sItem) => {
              let [x, y] = sItem.split('-');
              x = Number(x);
              y = Number(y);
              let cellInfo = state.dataJson.rows[y].cells[x];
              cellInfo.merge[0] = cellInfo.merge[0] - 1;
              let newHeight = calculateMergeCellHeight(y, cellInfo.merge);
              cellInfo.style.height = newHeight;
            });
          }

          state.dataJson.rows.splice(index, 1);

          // 处理删除行下面行数据 y坐标和mergeCell和eventConfig和query
          for (let i = index; i < state.dataJson.rows.length; i++) {
            const element = state.dataJson.rows[i].cells;
            element.map((eItem, eIndex) => {
              eItem.y = eItem.y - 1;
              if (eItem.mergeCell) {
                let [a, b] = eItem.mergeCell.split('-');
                a = Number(a);
                b = Number(b);
                eItem.mergeCell = a + '-' + (b > 0 ? b - 1 : b);
              }
              if (eItem.eventConfig && eItem.eventConfig.start) {
                eItem.eventConfig.start = true;
                let letter = eItem.eventConfig.targetCell.replace(/\d/g, '');
                let num = Number(eItem.eventConfig.targetCell.match(/\d+/g)[0]);
                eItem.eventConfig.targetCell = letter + (num - 1);
              }
              if (eItem.query) {
                let query = new Function('return ' + JSON.stringify(eItem.query))();
                let isDynamic = checkIsDynamicParams(query);
                if (isDynamic) {
                  let reg = /#{|}/g;
                  query.parameterDatas = query.parameterDatas.map((item) => {
                    let letters = item.value.replace(reg, '');
                    let letter = letters.replace(/\d/g, '');
                    let num = Number(letters.match(/\d+/g)[0]);
                    if (index < num) {
                      item.value = '#{' + letter + (num - 1) + '}';
                    }
                    return item;
                  });
                }
                eItem.query = query;
              }
            });
          }
          console.log(state.dataJson.rows, 'state.dataJson.rows');
        }
        // 检测是否为动态参数 如参数中包含#{A4}
        function checkIsDynamicParams(query) {
          if (Object.keys(query).length > 0) {
            for (const key in query) {
              let currentValue = query[key];
              if (typeof currentValue == 'string') {
                if (currentValue.startsWith('#{')) {
                  return true;
                }
              }
              if (Array.isArray(currentValue)) {
                let isDynamic = currentValue.some((item) => {
                  return checkIsDynamicParams(item);
                });
                if (isDynamic) {
                  return true;
                }
              }
            }
          }
        }
        function calculateMergeCellHeight(start, merge) {
          return state.yAxisNum
            .filter((item, index) => {
              return index >= start && index <= start + merge[0] - 1;
            })
            .reduce((pre, cur) => {
              return pre + cur.height;
            }, 0);
        }
      }
      initAxisAndHistroyData();
      function initAxisAndHistroyData() {
        if (state.dataJson.rows.length > 0) {
          that.commit('form/initAxis', {
            cellWidth: state.baseTableConfig.cellWidth,
            cellHeight: state.baseTableConfig.cellHeight
          });
        }
        that.commit('form/addHistroyData', {
          type: 'deleteRows',
          data: structuredClone(state.dataJson)
        });
      }
    },
    deleteColumns(state, config) {
      const that = this;
      let { index, count = 1 } = config;
      if (count == state.dataJson.rows[0].cells.length) {
        state.dataJson.rows = [];
      } else {
        if (count == 1) {
          deleteSingleColumn(index, 'single');
        } else {
          // 删除多列逻辑 从index+count-1列删除到index行
          for (let i = index + count - 1; i >= index; i--) {
            deleteSingleColumn(i, 'multiline');
          }
        }

        // 删除单列逻辑
        function deleteSingleColumn(index, mode = 'single') {
          let cells = [];
          // 针对当前列的处理逻辑
          state.dataJson.rows.map((rItem, rIndex) => {
            let cellInfo = rItem.cells[index];
            if (!cellInfo.hide && cellInfo.merge[0] == 1 && cellInfo.merge[1] == 1) {
              return false;
            } else {
              if (cellInfo.mergeCell) {
                cells.push(cellInfo.mergeCell);
              } else {
                if (!cellInfo.hide) {
                  cells.push(cellInfo.x + '-' + cellInfo.y);
                }
              }
            }
          });
          let setCells = [...new Set(cells)];
          console.log(setCells, 'setCells');
          let sameSetCells = [];
          state.dataJson.rows.map((rItem, rIndex) => {
            let cellInfo = rItem.cells[index];
            if (setCells.includes(cellInfo.x + '-' + cellInfo.y)) {
              sameSetCells.push(cellInfo.x + '-' + cellInfo.y);
            }
          });
          let otherSetCells = setCells.filter((item) => !sameSetCells.includes(item));
          // sameSetCells：当前单元格和左上单元格是同一个单元格，向右找单元格，将其colspan-1
          if (sameSetCells.length > 0) {
            sameSetCells.map((sItem) => {
              let [x, y] = sItem.split('-');
              x = Number(x);
              y = Number(y);
              if (x + 1 < state.dataJson.rows[y].cells.length && state.dataJson.rows[y].cells[index].merge[1] > 1) {
                let cellInfo = state.dataJson.rows[y].cells[index + 1];
                cellInfo.merge[0] = state.dataJson.rows[y].cells[index].merge[0];
                cellInfo.merge[1] = state.dataJson.rows[y].cells[index].merge[1] - 1;
                cellInfo.hide = false;
                delete cellInfo.mergeCell;
                let newWidth = calculateMergeCellWidth(x + 1, cellInfo.merge);
                cellInfo.style.width = newWidth;
              }
            });
          }

          // otherSetCells：当前单元格colspan-1
          if (otherSetCells.length > 0) {
            otherSetCells.map((sItem) => {
              let [x, y] = sItem.split('-');
              x = Number(x);
              y = Number(y);
              let cellInfo = state.dataJson.rows[y].cells[x];
              cellInfo.merge[1] = cellInfo.merge[1] - 1;
              let newWidth = calculateMergeCellWidth(x, cellInfo.merge);
              cellInfo.style.width = newWidth;
            });
          }

          state.dataJson.rows.map((rItem, rIndex) => {
            rItem.cells.splice(index, 1);
          });
          // 处理删除列右侧数据
          state.dataJson.rows.map((rItem, rIndex) => {
            rItem.cells.map((cItem, cIndex) => {
              if (cItem.x > index) {
                cItem.x = cItem.x - 1;
                if (cItem.mergeCell) {
                  let [a, b] = cItem.mergeCell.split('-');
                  a = Number(a);
                  b = Number(b);
                  cItem.mergeCell = (a > 0 ? a - 1 : a) + '-' + b;
                }
                if (cItem.eventConfig && cItem.eventConfig.start) {
                  cItem.eventConfig.start = true;
                  let letter = cItem.eventConfig.targetCell.replace(/\d/g, '');
                  let findIndex = state.letters.findIndex((item) => item == letter);
                  let num = Number(cItem.eventConfig.targetCell.match(/\d+/g)[0]);
                  if (findIndex > 0) {
                    cItem.eventConfig.targetCell = state.letters[findIndex - 1] + num;
                  }
                }
                if (cItem.query) {
                  let query = new Function('return ' + JSON.stringify(cItem.query))();
                  let isDynamic = checkIsDynamicParams(query);
                  if (isDynamic) {
                    let reg = /#{|}/g;
                    query.parameterDatas = query.parameterDatas.map((item) => {
                      let letters = item.value.replace(reg, '');
                      let letter = letters.replace(/\d/g, '');
                      let findIndex = state.letters.findIndex((item) => item == letter);
                      let num = Number(letters.match(/\d+/g)[0]);
                      item.value = '#{' + state.letters[findIndex - 1] + num + '}';
                      return item;
                    });
                  }
                  cItem.query = query;
                }
              }
            });
          });

          console.log(state.dataJson.rows, 'state.dataJson.rows');
        }

        // 检测是否为动态参数 如参数中包含#{A4}
        function checkIsDynamicParams(query) {
          if (Object.keys(query).length > 0) {
            for (const key in query) {
              let currentValue = query[key];
              if (typeof currentValue == 'string') {
                if (currentValue.startsWith('#{')) {
                  return true;
                }
              }
              if (Array.isArray(currentValue)) {
                let isDynamic = currentValue.some((item) => {
                  return checkIsDynamicParams(item);
                });
                if (isDynamic) {
                  return true;
                }
              }
            }
          }
        }
        function calculateMergeCellWidth(start, merge) {
          let widthArr = state.xAxisNum.filter((item, index) => {
            return index >= start && index <= start + merge[1] - 1;
          });
          return widthArr.reduce((pre, cur) => {
            return pre + cur.width;
          }, 0);
        }
      }
      initAxisAndHistroyData();
      function initAxisAndHistroyData() {
        if (state.dataJson.rows.length > 0) {
          that.commit('form/initAxis', {
            cellWidth: state.baseTableConfig.cellWidth,
            cellHeight: state.baseTableConfig.cellHeight
          });
        }
        that.commit('form/addHistroyData', {
          type: 'deleteColumns',
          data: structuredClone(state.dataJson)
        });
      }
    },
    addRows(state, config) {
      let { index, level = 'base' } = config;
      let { cellHeight, cellWidth, columns, rows } = state.baseTableConfig;
      let cells = [];
      // 针对当前行的处理逻辑
      state.dataJson.rows[index].cells.map((cItem, cIndex, array) => {
        if (!cItem.hide && cItem.merge[0] == 1 && cItem.merge[1] == 1) {
          // 显示和未合并的格子不做任何处理
          return false;
        } else {
          if (cItem.mergeCell) {
            cells.push(cItem.mergeCell);
          } else {
            if (!cItem.hide) {
              cells.push(cItem.x + '-' + cItem.y);
            }
          }
        }
      });
      let setCells = [...new Set(cells)];

      setCells.map((sItem) => {
        let [x, y] = sItem.split('-');
        let cellInfo = state.dataJson.rows[y].cells[x];
        cellInfo.merge[0] = cellInfo.merge[0] + 1;
        let newHeight = calculateMergeCellHeight(Number(y), cellInfo.merge);
        cellInfo.style.height = newHeight;
      });

      function calculateMergeCellHeight(start, merge) {
        return state.yAxisNum
          .filter((item, index) => {
            return index >= start && index <= start + merge[0] - 1;
          })
          .reduce((pre, cur) => {
            return pre + cur.height;
          }, 0);
      }
      let currentRowData = structuredClone(state.dataJson.rows[index]);
      let newRowData = {
        height: currentRowData.height,
        cells: currentRowData.cells.map((cItem) => {
          let obj = {
            ...cItem,
            isEdit: false,
            isLock: false,
            hide: cItem.hide ? true : cItem.merge[0] > 1 ? true : false,
            merge: [1, cItem.merge[1]],
            style: { width: cItem.style.width, height: cItem.style.height },
            value: '',
            code: '',
            dataType: level == 'base' ? '1' : cItem.dataType,
            dicData: level == 'base' ? [] : cItem.dicData,
            dicCode: '',
            type: level == 'base' ? 'text' : cItem.type,
            x: cItem.x,
            y: cItem.y + 1 // 更新行号
          };
          if (cItem.mergeCell) {
            obj.mergeCell = obj.mergeCell;
          } else {
            if (cItem.merge[0] > 1) {
              obj.mergeCell = cItem.x + '-' + cItem.y;
            }
          }
          if (cItem.eventConfig && cItem.eventConfig.start) {
            obj.eventConfig.start = true;
            let letter = cItem.eventConfig.targetCell.replace(/\d/g, '');
            obj.eventConfig.targetCell = letter + (Number(cItem.y) + 2);
          }
          if (cItem.query) {
            let query = new Function('return ' + JSON.stringify(cItem.query))();
            let isDynamic = checkIsDynamicParams(query);
            if (isDynamic) {
              let reg = /#{|}/g;
              query.parameterDatas = query.parameterDatas.map((item) => {
                let letters = item.value.replace(reg, '');
                let letter = letters.replace(/\d/g, '');
                item.value = '#{' + letter + (Number(cItem.y) + 2) + '}';
                return item;
              });
            }
            obj.query = query;
          }
          return obj;
        })
      };
      // 检测是否为动态参数 如参数中包含#{A4}
      function checkIsDynamicParams(query) {
        if (Object.keys(query).length > 0) {
          for (const key in query) {
            let currentValue = query[key];
            if (typeof currentValue == 'string') {
              if (currentValue.startsWith('#{')) {
                return true;
              }
            }
            if (Array.isArray(currentValue)) {
              let isDynamic = currentValue.some((item) => {
                return checkIsDynamicParams(item);
              });
              if (isDynamic) {
                return true;
              }
            }
          }
        }
      }
      console.log(newRowData, 'newRowData');
      // 更新index行下面行的 y坐标和mergeCell和eventConfig和query
      for (let i = index + 1; i < state.dataJson.rows.length; i++) {
        let cells = state.dataJson.rows[i].cells;
        cells.forEach((cell) => {
          cell.y++;
          if (cell.mergeCell) {
            let [a, b] = cell.mergeCell.split('-');
            cell.mergeCell = Number(a) + '-' + (Number(b) + 1);
          }
          if (cell.eventConfig && cell.eventConfig.start) {
            let targetCell = cell.eventConfig.targetCell;
            let letter = targetCell.replace(/\d/g, '');
            let num = Number(targetCell.match(/\d+/g)[0]);
            cell.eventConfig.targetCell = letter + (Number(num) + 1);
          }
          if (cell.query && cell.query.parameterDatas && cell.query.parameterDatas.length > 0) {
            cell.query.parameterDatas.map((param) => {
              let value = param.value;
              let letters = value.replace(/#{|}/g, '');
              let letter = letters.replace(/\d/g, '');
              let num = Number(letters.match(/\d+/g)[0]);
              if (index < num) {
                param.value = '#{' + letter + (num + 1) + '}';
              }
            });
          }
        });
      }
      // 插入新行
      state.dataJson.rows.splice(index + 1, 0, newRowData);
      // 重新计算坐标轴
      this.commit('form/initAxis', {
        cellWidth: state.baseTableConfig.cellWidth,
        cellHeight: state.baseTableConfig.cellHeight
      });
      console.log(state.dataJson.rows, 'state.dataJson.rows');
      // 记录历史操作
      this.commit('form/addHistroyData', {
        type: 'addRowsBottom',
        data: structuredClone(state.dataJson)
      });
    },
    addColumns(state, config) {
      let { index } = config;
      let { cellHeight, cellWidth, columns, rows } = state.baseTableConfig;
      let cells = [];
      // 针对当前列index的处理逻辑
      state.dataJson.rows.map((rItem, rIndex) => {
        if (!rItem.cells[index].hide && rItem.cells[index].merge[0] == 1 && rItem.cells[index].merge[1] == 1) {
          // 显示和未合并的格子不做任何处理
          return false;
        } else {
          if (rItem.cells[index].mergeCell) {
            cells.push(rItem.cells[index].mergeCell);
          } else {
            if (!rItem.cells[index].hide) {
              cells.push(rItem.cells[index].x + '-' + rItem.cells[index].y);
            }
          }
        }
      });
      let setCells = [...new Set(cells)];
      setCells.map((sItem) => {
        let [x, y] = sItem.split('-');
        let cellInfo = state.dataJson.rows[y].cells[x];
        cellInfo.merge[1] = cellInfo.merge[1] + 1;
        let newWidth = calculateMergeCellWidth(Number(x), cellInfo.merge);
        cellInfo.style.width = newWidth;
      });
      function calculateMergeCellWidth(start, merge) {
        let widthArr = state.xAxisNum.filter((item, index) => {
          return index >= start && index <= start + merge[1] - 1;
        });
        return widthArr.reduce((pre, cur) => {
          return pre + cur.width;
        }, 0);
      }

      // 向每行第index列插入一列数据
      state.dataJson.rows.map((rItem, rIndex) => {
        let newCellData = {
          ...rItem.cells[index],
          isEdit: false,
          isLock: false,
          hide: rItem.cells[index].hide ? true : rItem.cells[index].merge[1] > 1 ? true : false,
          merge: [rItem.cells[index].merge[0], 1],
          style: { width: rItem.cells[index].style.width, height: rItem.cells[index].style.height },
          value: '',
          code: '',
          dicData: [],
          dicCode: '',
          type: 'text',
          x: rItem.cells[index].x + 1,
          y: rItem.cells[index].y
        };
        if (rItem.cells[index].mergeCell) {
          newCellData.mergeCell = rItem.cells[index].mergeCell;
        } else {
          setCells.map((sItem) => {
            let [x, y] = sItem.split('-');
            x = Number(x);
            y = Number(y);
            if (x == rItem.cells[index].x && y == rItem.cells[index].y) {
              newCellData.mergeCell = rItem.cells[index].x + '-' + rItem.cells[index].y;
            }
          });
        }
        rItem.cells.splice(index + 1, 0, newCellData);
      });
      // 处理每行插入列右侧的列数据
      state.dataJson.rows.map((rItem, rIndex) => {
        rItem.cells.map((cItem, cIndex) => {
          if (cIndex > index + 1) {
            cItem.x = cItem.x + 1;
            if (cItem.mergeCell) {
              if (cItem.mergeCell.split('-')[0] > 1) {
                cItem.mergeCell = Number(cItem.mergeCell.split('-')[0]) + 1 + '-' + cItem.mergeCell.split('-')[1];
              }
            }
            // if (cIndex == rItem.cells.length - 1) {
            //   cItem.hide = false;
            // }
          }
        });
      });

      this.commit('form/initAxis', {
        cellWidth: state.baseTableConfig.cellWidth,
        cellHeight: state.baseTableConfig.cellHeight
      });
      console.log(state.dataJson.rows, 'state.dataJson.rows');
      this.commit('form/addHistroyData', {
        type: 'addColumns',
        data: structuredClone(state.dataJson)
      });
    },
    setBoxAreaXY(state, { x1, y1, x2, y2 }) {
      state.boxAreaXY = { startX: x1, startY: y1, endX: x2, endY: y2 };

      let endCell = state.dataJson.rows[y2].cells[x2];

      const width = Math.max(1, endCell.merge[1] > 1 ? x2 + endCell.merge[1] - x1 : x2 - x1 + 1);
      const height = Math.max(1, endCell.merge[0] > 1 ? y2 + endCell.merge[0] - y1 : y2 - y1 + 1);

      // 更新宽度和高度
      state.boxAreaXY.width = width;
      state.boxAreaXY.height = height;
    },
    clearBoxAreaXY(state, config) {
      // 定义框选区域的初始状态
      const initialBoxArea = {
        startX: 0,
        startY: 0,
        endX: 0,
        endY: 0,
        width: 1,
        height: 1
      };

      // 直接将初始状态赋给state.boxAreaXY
      state.boxAreaXY = initialBoxArea;
    },

    clearDesignerData(state) {
      Object.assign(state, {
        dataJson: {
          id: '',
          rows: [],
          colgroupWidth: [],
          merges: [],
          name: '',
          type: '',
          printConfig: {},
          tableTotalWidth: 0
        },
        apiJson: [],
        submitJson: {},
        dictJson: [],
        xAxisNum: [],
        yAxisNum: [],
        historyData: [],
        historyIndex: 0,
        coordArray: [],
        apiAllList: []
      });
      this.commit('form/clearCellInfo');
      this.commit('form/clearBoxAreaXY');
    },
    // 清除
    clearCellData(state, config) {
      const clearProperties = (cell) => {
        Object.assign(cell, {
          type: 'text',
          isLock: false,
          isEdit: false,
          apiField: false,
          isForamtter: false,
          code: '',
          value: '',
          dicCode: '',
          dicData: [],
          url: '',
          dataType: '1',
          dataFormatter: '',
          method: 'post',
          query: '',
          btnAddRowField: '',
          eventConfig: {}
        });
        const preserveStyle = { width: cell.style.width, height: cell.style.height };
        cell.style = preserveStyle;
      };
      // 清除选中单元格的属性
      clearProperties(state.cellInfo);
      if (state.cellInfo.x && state.cellInfo.y) {
        // 仅当选中单元格坐标有效时执行
        const cell = state.dataJson.rows[state.cellInfo.y - 1].cells[state.cellInfo.x - 1];
        clearProperties(cell);
      }
    },
    // 添加操作数据
    addHistroyData(state, { type, data }) {
      ++state.histroyIndex;
      state.histroyData.push({ type, data });
    },
    // 撤销
    undo(state, config) {
      if (state.histroyIndex > 1) {
        state.histroyIndex--;
        state.dataJson = structuredClone(state.histroyData[state.histroyIndex - 1].data);
        this.commit('form/initAxis', {
          cellWidth: state.baseTableConfig.cellWidth,
          cellHeight: state.baseTableConfig.cellHeight
        });
      } else {
        Message.warning('已经撤销到最开始的状态了！');
      }
    },
    // 重做
    redo(state, config) {
      if (state.histroyIndex < state.histroyData.length) {
        state.histroyIndex++;
        state.dataJson = structuredClone(state.histroyData[state.histroyIndex - 1].data);
        this.commit('form/initAxis', {
          cellWidth: state.baseTableConfig.cellWidth,
          cellHeight: state.baseTableConfig.cellHeight
        });
      } else {
        Message.warning('已经重做到最新的状态了！');
      }
    },
    // 打印设置
    setPrint(state, config) {
      state.dataJson.printConfig = {
        format: config.format || 'a4',
        orientation: config.orientation || 'portrait',
        width: config.width || 794,
        height: config.height || 1123
      };
    }
  }
};

export default designer;
